<template>
  <t-dialog
    v-model:visible="visible"
    :header="dialogTitle"
    mode="full-screen"
    :close-on-esc-keydown="false"
    :close-on-overlay-click="false"
    :confirm-btn="{ loading }"
    :footer="false"
  >
    <t-form
      ref="form"
      reset-type="initial"
      label-align="top"
      :data="formData"
      :rules="ARTICLE_FORM_RULES"
      class="layout"
      @submit="dialogConfirm"
    >
      <t-space direction="vertical">
        <t-row align="stretch" :gutter="20">
          <t-col :span="9">
            <t-form-item :label="t('common.title')" name="title">
              <t-input v-model="formData.title" maxlength="64" show-limit-number />
            </t-form-item>
            <t-form-item :label="t('common.description')" name="description">
              <t-textarea
                v-model="formData.description"
                :autosize="{ minRows: 2, maxRows: 5 }"
                maxlength="255"
                show-limit-number
              />
            </t-form-item>
            <t-form-item :label="t('pages.content.content')" class="editor" name="content.content">
              <ai-editor v-model="formData.content.content" />
            </t-form-item>
          </t-col>
          <t-col :span="3">
            <t-form-item :label="t('pages.content.cover')">
              <common-upload :url="formData.cover?.url" type="cover" @confirm="onChooseEnd" @remove="onChooseDel" />
            </t-form-item>
            <t-form-item :label="t('common.seoTitle')" name="seoTitle">
              <t-input v-model="formData.seoTitle" maxlength="28" show-limit-number />
            </t-form-item>
            <t-form-item :label="t('common.seoKeyword')" name="seoKeywords">
              <t-textarea
                v-model="formData.seoKeywords"
                :autosize="{ minRows: 2, maxRows: 5 }"
                maxlength="255"
                resize="none"
                show-limit-number
              />
            </t-form-item>
            <t-form-item :label="t('common.seoDescription')" name="seoDescription">
              <t-textarea
                v-model="formData.seoDescription"
                :autosize="{ minRows: 2, maxRows: 5 }"
                maxlength="255"
                resize="none"
                show-limit-number
              />
            </t-form-item>
            <t-form-item :label="t('pages.content.label')" name="tags">
              <t-select
                v-model="formData.tags"
                :options="tags"
                :loading="searchLoading"
                :keys="{ label: 'name', value: 'id' }"
                multiple
                filterable
                @search="onSearch"
              />
            </t-form-item>
          </t-col>
        </t-row>

        <t-row justify="center">
          <t-button theme="default" @click="dialogHide">{{ t('common.cancel') }}</t-button>
          <t-button theme="primary" type="submit">{{ t('common.save') }}</t-button>
        </t-row>
      </t-space>
    </t-form>
  </t-dialog>
</template>
<script setup lang="ts">
import { SelectProps } from 'tdesign-vue-next';
import { ref } from 'vue';

import $api from '@/api';
import AiEditor from '@/components/aieditor/index.vue';
import CommonUpload from '@/components/common-upload/index.vue';
import { t } from '@/locales';

import { ARTICLE_FORM_DATA, ARTICLE_FORM_RULES } from '../constants';

const loading = ref(false);
const emits = defineEmits(['confirm', 'removeFile']);

const dialogTitle = ref('');
const type = ref('add');
const visible = ref(false);
const form = ref(null);
const formData = ref({ ...ARTICLE_FORM_DATA });

const onChooseEnd = (type: 'cover', { id, url }: Recordable) => {
  formData.value[type] = { id, url };
};
const onChooseDel = (type: 'cover') => {
  formData.value[type] = null;
};

const tags = ref([]);
const searchLoading = ref(false);
const onSearch: SelectProps['onSearch'] = async (keyword) => {
  console.log(keyword);
  if (!keyword) {
    return;
  }
  searchLoading.value = true;
  const res = await $api.site.tag.list({ page: 1, limit: 10, name: keyword });
  tags.value = res?.items || [];
  searchLoading.value = false;
};

const dialogShow = (action: string, row: Recordable) => {
  visible.value = true;
  type.value = action;
  if (action === 'edit') {
    formData.value = JSON.parse(JSON.stringify(row));

    // tag
    formData.value.tags = row.tags.map((v: Recordable) => v.id);
    tags.value = row.tags;

    dialogTitle.value = `${t('common.edit')}【${row.title}】`;
  } else if (action === 'addchild') {
    formData.value.id = 0;

    dialogTitle.value = t('common.add');
  } else {
    dialogTitle.value = t('common.add');
  }
};
const dialogHide = () => {
  loading.value = false;
  form.value.reset();

  visible.value = false;
};
const dialogConfirm = async () => {
  const valid = await form.value.validate();

  if (valid !== true) {
    return;
  }
  loading.value = true;
  const res = JSON.parse(JSON.stringify(formData.value));

  emits('confirm', type.value, res);
};
const loadingClear = () => {
  loading.value = false;
};

defineExpose({
  dialogShow,
  dialogHide,
  loadingClear,
});
</script>

<style lang="less" scoped>
.layout {
  width: 1200px;
  margin: 0 auto !important;
}
</style>
